import store from '@/store'

/**
 * 界面按钮权限控制
 */
const hasPermission = {
    install(Vue) {
        Vue.directive('permission', {
            inserted: (el, binding, vnode) => {
                filterGlobalPermission(el, binding, vnode)
            }
        })
    }
}
/**
 * 界面按钮权限控制
 */
export const filterGlobalPermission = (el, binding) => {
    const { value } = binding
    const permissions = store.getters && store.getters.permissions
    if (value && value instanceof Array && value.length > 0) {
        const permissionRules = value
        const isPermission = permissions.some(permision => {
            return permissionRules.includes(permision)
        })
        if (!isPermission) {
            // el.parentNode && el.parentNode.removeChild(el)
            return false;
        }
    } else {
        throw new Error(`need permissions! Like v-permission="['edit','search']"`)
    }
}
export default hasPermission

/***
 * 用来控制按钮的disabled属性
 */
export function hasBtnPermission(permission) {
    const permissions = store.getters && store.getters.permissions
    if (permissions?.length == 0) {
        return true
    }
    if (permission && permission instanceof Array && permission.length > 0) {
        const permissionRules = permission
        const isPermission = permissions.some(item => {
            return permissionRules.includes(item)
        })
        if (!isPermission) {
            return true;
        }
    } else {
        // throw new Error(`need permissions`)
        return false;
    }
}